import React, { Component } from 'react'
import {
  Card,
  Form,
  Input,
  Cascader,
  Button,
  message
} from 'antd'
import PictoresWall from './PictoresWall'
import RichTextEditor from './RichTextEditor'
import { ArrowLeftOutlined } from '@ant-design/icons'
import { APIGetCategoryList, APIAddOrUpdateProduct } from '../../api'

const { Item } = Form
const { TextArea } = Input

export default class ProductAddUpdate extends Component {

  state = {
    options: []
  }
  constructor(props) {
    super(props)

    // 创建爱你用来保存ref表示的容器对象
    this.pw = React.createRef()
    this.editor = React.createRef()
  }

  // 更新展示分类列表
  initOptions = async (categoryList) => {
    // 根据categoryList展示options数组
    const options = categoryList.map(item => ({
      value: item._id,
      label: item.name,
      isLeaf: false
    }))
    // 如果是一个二级分类商品的更新
    const { product, isUpdate } = this
    const { pCategoryId } = product
    if(isUpdate && pCategoryId !== '0') {
      // 获取对应的二级分类列表
      const subCategoryList = await this.getCategoryList(pCategoryId)
      // 生成二次下拉列表的option
      const ChildOptions = subCategoryList.map(item => ({
        value: item._id,
        label: item.name,
        isLeaf: true
      }))
      // 找到当前商品对应的一级option对象
      const targetOption = options.find(option => option.value === pCategoryId)
      // 对应到对应的一级option上
      targetOption.children = ChildOptions
    }
    // 更新options状态
    this.setState({
      options
    })
  }

  // 获取分类列表方法
  getCategoryList = async (parentId) => {
    const { data } = await APIGetCategoryList(parentId)
    const categoryList = data
    if(parentId === '0') {
      // 更新一级分类列表
      this.initOptions(categoryList)
    } else {
      // 返回二级分类列表
      return categoryList
    }
  }

  // 表单提交数据处理
  submit = async (values) => {
    const imgArr = this.pw.current.getImgs()
    const imgs = JSON.stringify(imgArr)
    const detail = this.editor.current.getDetail()
    // 1. 收集所有数据，并封装成product对象
    const {name, desc, price, categoryIds} = values
    let pCategoryId, categoryId
    if(categoryIds.length === 1) {
      pCategoryId = '0'
      categoryId = categoryIds[0]
    } else {
      pCategoryId = categoryIds[0]
      categoryId = categoryIds[1]
    }
    const product = {
      name,
      desc,
      price,
      pCategoryId,
      categoryId,
      imgs,
      detail
    }
    if(this.isUpdate) {
      product._id = this.product._id
    }
    // 2. 调用接口请求函数
    const result = await APIAddOrUpdateProduct(product)

    // 3. 根据结果提示
    if(result.status === 0) {
      message.success(`${this.isUpdate ? '更新' : '添加'}商品成功！`)
      this.props.history.go(-1)
    } else {
      message.error(`${this.isUpdate ? '更新' : '添加'}商品失败！`)
    }
  }

  // 用于加载下一级列表的回调函数
  loadData = async selectedOptions => {
    // 得到选择的Option对象
    const targetOption = selectedOptions[0];
    targetOption.loading = true
     // 发送异步请求，获取二级列表
    const subCategoryList = await this.getCategoryList(targetOption.value)
    targetOption.loading = false
    if(subCategoryList && subCategoryList.length > 0) {
      // 生成一个二级列表的options
      const childOptions = subCategoryList.map(item => ({
        value: item._id,
        label: item.name,
        isLeaf: true
      }))
      // 将此二级列表关联到当前一级列表上去
      targetOption.children = childOptions
    } else { //没有二次分类
      targetOption.isLeaf = true
    }
    this.setState({
      options: [...this.state.options]
    })
  };

  componentDidMount() {
    this.getCategoryList('0')
  }

  render() {
    const { options } = this.state
    this.product = this.props.location.state || {}
    const { pCategoryId, categoryId } = this.product
    // 用来接收级联分类Id
    const categoryIds = []

    this.isUpdate = !!this.product.pCategoryId
    if(this.isUpdate) {
      if(pCategoryId === '0') {
        // 一级分类商品
        categoryIds.push(categoryId)
      } else {
        // 二级分类商品
        categoryIds.push(pCategoryId)
        categoryIds.push(categoryId)
      }  
    }
    
    const title = (
      <span>
      <Button type="link" onClick={()=>{this.props.history.go(-1)}}>
        <ArrowLeftOutlined style={{color: 'green', marginRight: 15, fontSize: 20}}/>
      </Button>
      <span>{this.isUpdate ? '修改商品' : '添加商品'}</span>
    </span>
    )
    return (
      <Card title={title}>
        <Form
          onFinish={this.submit}
          labelCol={{
            span: 4,
          }}
          wrapperCol={{
            span: 12,
          }}
        >
          <Item 
            label="商品名称"
            initialValue={this.product.name}
            name="name"
            rules={[{ required: true, message: '请输入商品名称!' }]}
          >
            <Input placeholder="请输入商品名称" />
          </Item>
          <Item 
            label="商品描述"
            initialValue={this.product.desc}
            name="desc"
            rules={[{ required: true, message: '请输入商品描述!' }]}
          >
            <TextArea placeholder="请输入商品描述" autoSize={{ minRows: 2, maxRows: 6 }}/>
          </Item>
          <Item 
            label="商品价格"
            initialValue={this.product.price}
            name="price"
            rules={[
              { 
                required: true, 
                message: '请输入商品价格!' 
              },
              {
                validator: (_, value) =>
                  value*1 > 0 ? Promise.resolve() : Promise.reject(new Error('价格必须大于0')),
              }
            ]}
          >
            <Input addonAfter="元" type="number" placeholder="请输入商品价格" />
          </Item>
          <Item 
            label="商品分类"
            initialValue={categoryIds}
            name="categoryIds"
            rules={[{ required: true, message: '请指定商品分类!' }]}
          >
            <Cascader 
              placeholder="请指定商品分类"
              options={options} 
              loadData={this.loadData}
            />
          </Item>
          <Item 
            label="商品图片"
          >
            <PictoresWall ref={this.pw} imags={this.product.imgs}/>
          </Item>
          <Item 
            name="detail"
            label="商品详情"
            labelCol={{
              span: 4,
            }}
            wrapperCol={{
              span: 18,
            }}
          >
            <RichTextEditor ref={this.editor} detail={this.product.detail}/>
          </Item>
          <Item>
            <Button style={{marginLeft: 100}} type="primary" htmlType="submit">提交</Button>
          </Item>
          
        </Form>
      </Card>
    )
  }
}
